#include "chatserver.hpp"
#include "json.hpp"
#include "chatservice.hpp"

#include <functional>
#include <string>
using namespace std;
using namespace placeholders;
using json = nlohmann::json;

ChatServer::ChatServer(EventLoop *loop,
                       const InetAddress &listenAddr,
                       const string &nameArg)
    : _server(loop, listenAddr, nameArg), _loop(loop)
{
    // 回调函数
    auto connection_callback = [this](const TcpConnectionPtr &conn)
    { return this->onConnection(conn); };
    auto message_callback = [this](const TcpConnectionPtr &conn, Buffer *buffer, Timestamp time)
    { return this->onMessage(conn, buffer, time); };

    _server.setConnectionCallback(connection_callback);
    _server.setMessageCallback(message_callback);
    _server.setThreadNum(4);
}

void ChatServer::start()
{
    _server.start();
}

// 手写以下两个函数，将网络层与业务层区解耦
void ChatServer::onConnection(const TcpConnectionPtr &conn)
{
    // 客户端断开链接
    if (!conn->connected())
    {
        ChatService::instance()->clientCloseException(conn);
        conn->shutdown();
    }
}

void ChatServer::onMessage(const TcpConnectionPtr &conn,
                           Buffer *buffer,
                           Timestamp time)
{
    string buf = buffer->retrieveAllAsString();

    json js = json::parse(buf);
    auto msgHandler = ChatService::instance()->getHandler(js["msgid"].get<int>());
    // 回调消息绑定好的事件处理器，来执行相应的业务逻辑
    msgHandler(conn, js, time);
}
